package com.example.base.security.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.base.security.domain.vo.LoginVo;
import com.example.base.security.service.LoginService;
import com.example.base.utils.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/u")
public class SysLoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private LoginService loginService;

    @PostMapping("login")
    public void loginController(HttpServletRequest request,
                                      HttpServletResponse response,
                                      @RequestBody LoginVo vo){
        try {
            Authentication authenticate =authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(vo.getUsername(), vo.getPassword())
            );
            loginService.loginSuccess(response,authenticate);
        }catch (AuthenticationException exception){
            loginService.loginFail(exception,response);
        }
    }

    @PostMapping("/userLogout")
    public void userLogoutController(HttpServletRequest request,HttpServletResponse httpServletResponse){
        loginService.loginOutSucess(request,httpServletResponse);
    }




}
